package com.northpool.operator.common.string;

import cn.hutool.core.compiler.CompilerUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;

import java.lang.reflect.Method;

@OperatorInfo(ref = "StringOperator", name = "字符串工具", description = "字符串拼接、处理等")
@OutputParams({
        @OutputParam(ref = "result", name = "处理过后的字符串", desc = "处理过后的字符串")
})
public class StringOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "expression", name = "字符串处理表达式", desc = "字符串处理表达式，仅支持Java语法，不能以括号开头。如：'\"abcde\".substring(0,3).toUpperCase()'")
    })
    public StringOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(StringOperator.class,
                TestParamBuilder.aBuilder()
                        .param("expression", "\"abcde\".substring(0,3).toUpperCase()")
                        .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String expression = paramTool.getStr("expression");
        if (StrUtil.isBlank(expression)) {
            System.out.println("error: 表达式不能为空");
            this.failedExit();
        }
        String result = this.formatString(expression);
        this.result("result", result);
    }

    public String formatString(String expression) throws ClassNotFoundException {
        String javaCode =
                "public class StringJava {\n" +
                        "public String run() {\n" +
                        "   return " + expression + ";\n" +
                        "}\n" +
                        "}";
        ClassLoader compile = compile(javaCode);
        final Class<?> cla = compile.loadClass("StringJava");
        return exec(cla);
    }

    public ClassLoader compile(String javaCode) {
        return CompilerUtil.getCompiler(null)
                // 被编译的源码字符串
                .addSource("StringJava", javaCode)
                .compile();
    }

    public String exec(Class<?> cla) {
        try {
            Object o = cla.getDeclaredConstructor().newInstance();
            Method method = cla.getMethod("run");
            return (String) method.invoke(o);
        } catch (Exception e) {
            System.out.println("error: 表达式执行失败");
            this.error(ExceptionUtil.getMessage(e));
            System.exit(1);
        }
        return null;
    }
}
